<template>
  <div>
    <!-- 面包屑导航区域 -->
    <el-breadcrumb separator-class="el-icon-arrow-right">
      <el-breadcrumb-item :to="{ path: '/home' }">首页</el-breadcrumb-item>
      <el-breadcrumb-item>权限管理</el-breadcrumb-item>
      <el-breadcrumb-item>角色列表</el-breadcrumb-item>
    </el-breadcrumb>

    <!-- 卡片试图区域 -->
    <el-card>
      <!-- 添加用户按钮 -->
      <el-button type="primary" @click="dialogVisible = !dialogVisible"
        >添加角色</el-button
      >
      <!-- 用户列表区域 -->
      <el-table :data="rightslist" border stripe>
        <!-- 展开列 -->
        <el-table-column type="expand">
          <template slot-scope="scope">
            <el-row
              :class="['bdborder', index == 0 ? 'dbborder' : '', 'vcenter']"
              v-for="(item1, index) in scope.row.children"
              :key="item1.id"
            >
              <!-- 渲染一级权限 -->
              <el-col :span="6">
                <el-tag closable @close="rolesDele(scope.row.id, item1.id)">{{
                  item1.authName
                }}</el-tag>
                <i class="el-icon-caret-right"></i>
              </el-col>
              <!-- 渲染二级和三级权限 -->
              <el-col :span="18">
                <el-row
                  :class="[index == 0 ? '' : 'dbborder', 'vcenter']"
                  v-for="(item2, index) in item1.children"
                  :key="item2.id"
                >
                  <!-- 渲染二级权限 -->
                  <el-col :span="6">
                    <el-tag
                      type="success"
                      closable
                      @close="rolesDele(scope.row.id, item2.id)"
                      >{{ item2.authName }}</el-tag
                    >
                    <i class="el-icon-caret-right"></i>
                  </el-col>
                  <!-- 渲染三级权限 -->
                  <el-col :span="18">
                    <el-tag
                      @close="rolesDele(scope.row.id, item3.id)"
                      closable
                      type="warning"
                      v-for="item3 in item2.children"
                      :key="item3.id"
                      >{{ item3.authName }}</el-tag
                    >
                  </el-col>
                </el-row>
              </el-col>
            </el-row>
          </template>
        </el-table-column>
        <!-- 索引列 -->
        <el-table-column type="index" label="#"></el-table-column>
        <el-table-column label="角色名称" prop="roleName"></el-table-column>
        <el-table-column label="描述" prop="roleDesc"></el-table-column>
        <el-table-column label="操作">
          <template slot-scope="scope">
            <!-- 编辑按钮 -->
            <el-button
              type="primary"
              icon="el-icon-edit"
              size="mini"
              @click="butModify(scope.row.id)"
              >编辑</el-button
            >
            <!-- 删除按钮 -->
            <el-button
              type="danger"
              icon="el-icon-delete"
              size="mini"
              @click="removeDele(scope.row.id)"
              >删除</el-button
            >
            <!-- 分配权限按钮 -->
            <el-button
              type="warning"
              icon="el-icon-setting"
              size="mini"
              @click="butDistribution(scope.row)"
              >分配权限</el-button
            >
          </template>
        </el-table-column>
      </el-table>
    </el-card>

    <!-- 添加用户对话框 -->
    <el-dialog
      title="添加新角色"
      :visible.sync="dialogVisible"
      width="50%"
      @close="dialogClose"
      :lock-scroll="false"
    >
      <!-- 内容主体区域 -->
      <el-form
        :model="ruleForm"
        :rules="rules"
        ref="ruleForm"
        label-width="80px"
        status-icon
      >
        <el-form-item label="角色名称" prop="roleName">
          <el-input v-model="ruleForm.roleName"></el-input>
        </el-form-item>
        <el-form-item label="角色描述" prop="roleDesc">
          <el-input v-model="ruleForm.roleDesc"></el-input>
        </el-form-item>
      </el-form>
      <!--  底部按钮区域 -->
      <span slot="footer" class="dialog-footer">
        <el-button @click="dialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="addUser('ruleForm')">确定</el-button>
      </span>
    </el-dialog>

    <!-- 编辑用户对话框 -->
    <el-dialog
      title="编辑角色信息"
      :visible.sync="dialogModify"
      width="50%"
      @close="modifyClose"
      :lock-scroll="false"
    >
      <!-- 内容主体区域 -->
      <el-form
        :model="rolesModify"
        :rules="rules"
        ref="rolesModify"
        label-width="80px"
        status-icon
      >
        <el-form-item label="角色名称" prop="roleName">
          <el-input v-model="rolesModify.roleName"></el-input>
        </el-form-item>
        <el-form-item label="角色描述" prop="roleDesc">
          <el-input v-model="rolesModify.roleDesc"></el-input>
        </el-form-item>
      </el-form>
      <!--  底部按钮区域 -->
      <span slot="footer" class="dialog-footer">
        <el-button @click="dialogModify = false">取 消</el-button>
        <el-button type="primary" @click="butdialog('rolesModify')"
          >确 定</el-button
        >
      </span>
    </el-dialog>

    <!-- 分配权限对话框 -->
    <el-dialog
      title="分配角色权限"
      :visible.sync="distribution"
      width="50%"
      @close="distributionoOt"
    >
      <!-- 树形控件 -->
      <el-tree
        :default-checked-keys="defKeys"
        node-key="id"
        :data="distributionList"
        :props="treeProps"
        show-checkbox
        ref="treeRef"
      ></el-tree>
      <!--  底部按钮区域 -->
      <span slot="footer" class="dialog-footer">
        <el-button @click="distribution = false">取 消</el-button>
        <el-button type="primary" @click="allotRights">确 定</el-button>
      </span>
    </el-dialog>
  </div>
</template>

<script>
export default {
  data() {
    return {
      // 控制对话框的显示与隐藏
      dialogVisible: false,
      // 控制编辑用户对话框的显示与隐藏
      dialogModify: false,
      // 控制分配权限对话框显示与隐藏
      distribution: false,
      // 添加用户表单的数据
      ruleForm: {
        roleName: "",
        roleDesc: ""
      },
      // 表单的验证规则
      rules: {
        roleName: [
          { required: true, message: "请输入角色名称", trigger: "blur" },
          { min: 2, max: 10, message: "长度在 2 到 10 个字符", trigger: "blur" }
        ],
        roleDesc: [
          { required: true, message: "请输入角色描述", trigger: "blur" },
          { min: 2, max: 10, message: "长度在 2 到 10 个字符", trigger: "blur" }
        ]
      },
      // 所有角色列表数据
      rightslist: [],
      // 编辑对话框用户信息数据
      rolesModify: {},
      // 分配权限信息数据
      distributionList: [],
      // 树形结构属性绑定
      treeProps: {
        label: "authName",
        children: "children"
      },
      // 树形结构默认勾选已有权限
      defKeys: [],
      // 当前即将分配权限的角色id
      roleId: ""
    };
  },
  methods: {
    dialogClose() {
      // 当对话框关闭时会触发表单重置事件
      this.$refs.ruleForm.resetFields();
    },
    modifyClose() {
      // 当修改对话框关闭时会触发表单重置事件
      this.$refs.rolesModify.resetFields();
    },
    distributionoOt() {
      this.defKeys = [];
    },
    // 分配权限接口
    async butDistribution(role) {
      const result = await this.$http.get("rights/tree");
      if (result.meta.status == 200) {
        this.distributionList = result.data;
        this.roleId = role.id;
      } else {
        this.$message.error("分配权限数据获取失败！");
      }
      // 递归获取三级节点的Id
      this.getLeafKeys(role, this.defKeys);

      this.distribution = !this.distribution;
    },
    // 通过递归的形式，获取角色下所有三级权限的id，并保存到 defKeys 数组中
    getLeafKeys(node, arr) {
      // 如果当前 node 节点不包含 children 属性，则是三级节点
      if (node.children) {
        node.children.forEach(item => this.getLeafKeys(item, arr));
      } else {
        arr.push(node.id);
      }
    },
    // 点击确定按钮为角色分配权限
    async allotRights() {
      const keys = [
        ...this.$refs.treeRef.getCheckedKeys(),
        ...this.$refs.treeRef.getHalfCheckedKeys()
      ];

      const idStr = keys.join(",");

      const result = await this.$http.post(`roles/${this.roleId}/rights`, {
        rids: idStr
      });

      if (result.meta.status == 200) {
        this.$message.success("分配权限成功！");
        this.rightsList();
        this.distribution = !this.distribution;
      } else {
        this.$message.error("分配权限失败！");
      }
    },
    // 添加用户接口
    addUser(ruleForm) {
      console.log(this.ruleForm);
      this.$refs[ruleForm].validate(async valid => {
        if (valid) {
          // 验证通过发起网络接口请求
          const result = await this.$http.post("roles", this.ruleForm);
          if (result.meta.status == 201) {
            this.$message.success("用户创建成功！");
            this.dialogVisible = !this.dialogVisible; //创建成功对话框隐藏
            this.rightsList(); //重新加载列表数据
          } else {
            this.$message.error("用户创建失败！");
          }
        }
      });
    },
    // 获取所有角色列表接口
    async rightsList() {
      const reslut = await this.$http.get("roles");
      if (reslut.meta.status == 200) {
        this.rightslist = reslut.data;
      } else {
        this.$message.error("获取数据失败！");
      }
    },
    // 点击编辑按钮获取当前用户信息接口
    async butModify(id) {
      const result = await this.$http.get("roles/" + id);
      if (result.meta.status == 200) {
        this.rolesModify = result.data;
        this.dialogModify = !this.dialogModify;
      } else {
        {
          this.$message.error("获取数据失败！");
        }
      }
    },
    // 编辑用户角色信息并提交接口
    butdialog(rolesModify) {
      this.$refs[rolesModify].validate(async valid => {
        if (valid) {
          // 验证通过发起网络接口请求
          const result = await this.$http.put(
            "roles/" + this.rolesModify.roleId,
            this.rolesModify
          );
          if (result.meta.status == 200) {
            this.$message.success("用户信息修改成功！");
            this.dialogModify = !this.dialogModify; //创建成功对话框隐藏
            this.rightsList(); //重新加载列表数据
          } else {
            this.$message.error("用户创建失败！");
          }
        }
      });
    },
    // 删除按钮事件
    async removeDele(id) {
      // 弹框询问用户是否删除数据
      const res = await this.$confirm(
        "此操作将永久删除该用户, 是否继续?",
        "提示",
        {
          confirmButtonText: "确定",
          cancelButtonText: "取消",
          type: "warning",
          lockScroll: false
        }
      ).catch(err => err);
      console.log(res);
      console.log(id);
      // 如果用户确认删除，则返回值为字符串 confirm
      // 如果用户取消了删除，则返回值为字符串 cancel
      if (res == "cancel") {
        this.$message.warning("您已取消删除操作！");
      } else {
        const reslut = await this.$http.delete("roles/" + id);
        if (reslut.meta.status == 200) {
          this.rightsList();
          this.$message.success("您已删除该用户！");
        } else {
          this.$message.error("删除失败！");
        }
      }
    },
    // 删除指定角色权限接口
    async rolesDele(roleId, rightId) {
      // 弹框询问用户是否删除数据
      const res = await this.$confirm(
        "此操作将永久删除该用户, 是否继续?",
        "提示",
        {
          confirmButtonText: "确定",
          cancelButtonText: "取消",
          type: "warning"
        }
      ).catch(err => err);
      console.log(res);
      // 如果用户确认删除，则返回值为字符串 confirm
      // 如果用户取消了删除，则返回值为字符串 cancel
      if (res == "cancel") {
        this.$message.warning("您已取消删除操作！");
      } else {
        const reslut = await this.$http.delete(
          `roles/${roleId}/rights/${rightId}`
        );
        if (reslut.meta.status == 200) {
          this.rightsList();
          this.$message.success("您已删除该权限！");
        } else {
          this.$message.error("删除失败！");
        }
      }
    }
  },
  created() {
    this.rightsList();
  }
};
</script>

<style lang="stylus" scoped>
.el-tag {
  margin: 6px;
}

.bdborder {
  border-bottom: 1px solid #eee;
  padding: 6px;
}

.dbborder {
  border-top: 1px solid #eee;
}

.vcenter {
  display: flex;
  align-items: center;
}
</style>
